from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from django.urls import reverse

# Create your models here.

class Category(models.Model):
    class Meta:
        verbose_name = "分类"
        verbose_name_plural = verbose_name
        
    category = models.CharField(max_length=20)
    
    def __str__(self):
        return self.category
    
class Tag(models.Model):
    class Meta:
        verbose_name = "标签"
        verbose_name_plural = verbose_name
    
    tag = models.CharField(max_length=20)
    
    def __str__(self):
        return self.tag

class BlogArticle(models.Model):
    class Meta:
        verbose_name = "博客文章"
        verbose_name_plural = verbose_name
        ordering = ('-createTime',)
    
    title = models.CharField("标题", max_length=200)
    body = models.TextField("正文")
    createTime = models.DateTimeField("创建时间", default=timezone.now)
    updateTime = models.DateTimeField("修改时间", auto_now=True)
    author = models.ForeignKey(User, verbose_name="作者", on_delete=models.CASCADE)
    category = models.ForeignKey(Category, verbose_name="分类", on_delete=models.CASCADE, blank=True, null=True)
    tags = models.ManyToManyField(Tag, verbose_name="标签", blank=True)
    views = models.PositiveIntegerField("阅读次数", default=0, editable=False)
    
    def __str__(self):
        return self.title
    
    def get_absolute_url(self):
        return reverse('blog:detail', kwargs={'pk': self.pk})
    
    def increase_views(self):
        self.views += 1
        self.save(update_fields=['views'])
